<template>
  <div class="wrap">
    <div class="wrap-button">
      <a-button style="margin-right: 8px" type="primary" @click="showAddContract">上传</a-button>
      <div style="float: right">
        <a-range-picker v-model:value="searchDate" style="margin-right: 8px" />
        <a-input
          v-model:value="keyword"
          style="width: 180px; margin-right: 8px"
          placeholder="输入关键字查询"
          allow-clear
        >
          <template #prefix>
            <SearchOutlined style="color: #666" />
          </template>
        </a-input>
        <a-button type="primary" @click="handleSearch">查询</a-button>
      </div>
    </div>
    <div class="wrap-table">
      <!-- <BaseTitle title="用户列表" /> -->
      <a-table
        :loading="loading"
        :dataSource="data"
        :columns="columns"
        :pagination="pagination"
        size="middle"
        @change="handleTableChange"
        width="300"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'isLock'">
            <a-tag v-if="record.isLock === '0'" color="cyan">正常</a-tag>
            <a-tag v-else color="red">锁定</a-tag>
          </template>
          <template v-if="column.key === 'operation'">
            <!-- <a-button class="button-interval" type="link" :icon="h(FileTextOutlined)" size="small">
              查看
            </a-button> -->
            <a-button
              class="button-interval"
              type="link"
              size="small"
              @click="handleSetting(record)"
            >
              查看
            </a-button>
            <a-button
              class="button-interval"
              type="link"
              size="small"
              @click="handleSetting(record)"
            >
              下载
            </a-button>
            <a-button
              class="button-interval"
              type="link"
              size="small"
              @click="handleSetting(record)"
            >
              文字识别
            </a-button>
            <a-button
              class="button-interval"
              type="link"
              size="small"
              @click="handleDeleteUser(record)"
            >
              删除
            </a-button>
          </template>
        </template>
      </a-table>
      <a-modal v-model:visible="open" title="上传资料" @ok="handleAddSubmit">
        <a-form
          ref="formRef"
          style="margin-top: 24px"
          :model="formState"
          name="basic"
          :label-col="{ span: 5 }"
          :wrapper-col="{ span: 17 }"
          autocomplete="off"
        >
          <a-form-item
            label="合同名称"
            name="contractName"
            :rules="[{ required: true, message: 'Please input your contractName!' }]"
          >
            <a-input
              readOnly
              onfocus="this.removeAttribute('readonly');"
              onblur="this.setAttribute('readonly',true);"
              v-model:value="formState.contractName"
            />
          </a-form-item>
          <a-form-item label="资料时间" name="contractTime">
            <a-date-picker v-model:value="dateValue" />
          </a-form-item>

          <a-form-item
            label="所属用户"
            name="userId"
            :rules="[{ required: true, message: 'Please input your userId!' }]"
          >
            <a-input
              readOnly
              onfocus="this.removeAttribute('readonly');"
              onblur="this.setAttribute('readonly',true);"
              v-model:value="formState.userId"
            />
          </a-form-item>
        </a-form>
        <div style="margin-left: 24px; margin-right: 24px">
          <a-upload-dragger
            v-model:fileList="fileList"
            name="file"
            :multiple="true"
            action="/basic-api/contract/uploadFile"
            :headers="{
              authorization: 'Bearer ' + getToken(),
            }"
            @change="handleChange"
          >
            <p class="ant-upload-drag-icon">
              <inbox-outlined></inbox-outlined>
            </p>
            <p class="ant-upload-text">Click or drag file to this area to upload</p>
            <p class="ant-upload-hint">
              Support for a single or bulk upload. Strictly prohibit from uploading company data or
              other band files
            </p>
          </a-upload-dragger>
        </div>
      </a-modal>
    </div>
  </div>
</template>

<script lang="ts" setup>
  import { ref, unref, computed, onMounted, reactive, watch } from 'vue'
  import { SearchOutlined, InboxOutlined } from '@ant-design/icons-vue'
  import { FormInstance, message } from 'ant-design-vue'
  import type { UploadChangeParam } from 'ant-design-vue'
  import { GetUserListModel, FormState } from '/@/api/sys/model/userModel'
  import { UserRoleModel } from '/@/api/sys/model/roleModel'
  import {
    ConstractVo,
    ConstractSo,
    ContractUploadBO,
    ContractUploadFileBO,
  } from '/@/api/contract/model/contractModel'
  import { getUserList, addUser, deleteUser } from '/@/api/sys/user'
  import { pageContractApi, uploadContractApi } from '/@/api/contract'
  import { Modal } from 'ant-design-vue'
  import type { Dayjs } from 'dayjs'
  import dayjs from 'dayjs'
  import { getToken } from '/@/utils/auth'

  const open = ref<boolean>(false)
  const settingUserId = ref<string>('')
  const loading = ref(false)
  const keyword = ref<string>('')
  type RangeValue = [Dayjs, Dayjs]
  const searchDate = ref<RangeValue>()
  const dateValue = ref<Dayjs>()
  const fileList = ref([])
  const fileResultList = ref<ContractUploadFileBO[]>([])
  const uploadBo = reactive<ContractUploadBO>({
    contractName: '', // Check here to configure the default column
    contractTime: '',
    userId: '',
    files: [],
  })

  const columns = [
    {
      title: '资料名称',
      dataIndex: 'contractName',
      key: 'contractName',
      align: 'center',
    },
    {
      title: '资料时间',
      dataIndex: 'contractTime',
      key: 'contractTime',
      align: 'center',
      width: 140,
      // customCell: (text) => (text ? (text == '周沈斌' ? '我变变变' : text) : '--'),
    },
    {
      title: '所属用户',
      dataIndex: 'ownUserName',
      key: 'ownUserName',
      align: 'center',
      width: 180,
    },
    {
      title: '文件类型',
      dataIndex: 'fileType',
      key: 'fileType',
      align: 'center',
      width: 140,
      // customCell: (text) => (text ? (text == '周沈斌' ? '我变变变' : text) : '--'),
    },
    {
      title: '文件大小',
      dataIndex: 'fileSize',
      key: 'fileSize',
      align: 'center',
      width: 140,
      // customCell: (text) => (text ? (text == '周沈斌' ? '我变变变' : text) : '--'),
    },
    {
      title: '上传时间',
      dataIndex: 'uploadTime',
      key: 'uploadTime',
      align: 'center',
      width: 180,
    },
    {
      title: '操作',
      key: 'operation',
      fixed: 'right',
      align: 'center',
      width: 250,
    },
  ]

  watch(dateValue, (newValue, oldValue) => {
    console.log(`新值: ${newValue}, 旧值: ${oldValue}`)
    formState.contractTime = dayjs(newValue).format('YYYY-MM-DD')
  })

  let data = ref<ConstractVo[]>([])
  const pagination = ref({
    total: 0,
    current: 1,
    pageSize: 10,
    size: '',
    showSizeChanger: false,
    showQuickJumper: false,
  })

  const pageParam = computed(() => ({
    query: {
      keyword: unref<string>(keyword),
      contractStartTime: searchDate.value?.[0]
        ? dayjs(searchDate.value?.[0]).format('YYYY-MM-DD')
        : null,
      contractEndTime: searchDate.value?.[1]
        ? dayjs(searchDate.value?.[1]).format('YYYY-MM-DD')
        : null,
      uploadStartTime: undefined,
      uploadEndTime: undefined,
      clienteleId: undefined,
    },
    current: pagination.value?.current,
    size: pagination.value?.pageSize,
  }))

  const userRoleParam = computed<UserRoleModel>(() => ({
    userId: unref(settingUserId),
    roleIds: state.selectedRowKeys,
  }))

  //#endregion

  const state = reactive<{
    selectedRowKeys: string[]
    loading: boolean
  }>({
    selectedRowKeys: [], // Check here to configure the default column
    loading: false,
  })

  onMounted(() => {
    list()
  })

  const handleSearch = () => {
    list()
  }

  async function list() {
    loading.value = true
    const res = await pageContractApi(unref(pageParam))
    data.value = res.records
    pagination.value.total = Number(res.total)
    pagination.value.current = Number(res.current)
    loading.value = false
  }

  function handleTableChange(page) {
    pagination.value.current = page.current
    list()
  }

  //#region 用户

  const formRef = ref<FormInstance>()

  let formState = reactive<FormState>({
    contractName: '',
    contractTime: '',
    userId: '',
  })

  async function showAddContract() {
    open.value = true
    dateValue.value = undefined
    formRef.value?.resetFields()
  }

  const handleAddSubmit = () => {
    formRef.value
      ?.validateFields()
      .then(() => {
        uploadBo.contractName = formState.contractName
        uploadBo.contractTime = formState.contractTime
        uploadBo.userId = formState.userId
        uploadBo.files = fileResultList.value
        console.log('fileResultList', fileResultList)
        uploadContractApi(uploadBo).then(() => {
          message.success('上传成功')
        })
        // addUser(formState).then(() => {
        //   message.success('添加成功')
        //   open.value = false
        //   list()
        // })
      })
      .catch(() => {
        message.error('表单填写错误')
      })
  }

  const handleDeleteUser = (record: any) => {
    Modal.confirm({
      title: '提示',
      maskClosable: true,
      content: '确定要删除该用户吗？',
      onOk() {
        deleteUser(record.id).then(() => {
          list()
          message.success('删除成功')
        })
      },
      onCancel() {},
    })
  }

  const onSelectChange = (selectedRowKeys: string[]) => {
    console.log('selectedRowKeys changed: ', selectedRowKeys)
    state.selectedRowKeys = selectedRowKeys
  }

  const handleChange = (info: UploadChangeParam) => {
    console.log('handleChange info', info)
    if (info.file.status !== 'uploading') {
      console.log(info.file, info.fileList)
    }
    if (info.file.status === 'done') {
      message.success(`${info.file.name} file uploaded successfully`)
      console.log(info.file.response.result)
      fileResultList.value.push(info.file.response.result)
    } else if (info.file.status === 'error') {
      message.error(`${info.file.name} file upload failed.`)
    }
  }

  // const customRequest = () => {
  //   const form = new FormData()
  //   form.append('file', file.file)
  //   // uploadFile 我自己的接口
  //   uploadContractApi(form).then((res) => {
  //     if (res.success) {
  //       // 调用组件内方法, 设置为成功状态
  //       file.onSuccess(res, file.file)
  //       file.status = 'done'
  //     } else {
  //       file.onError()
  //       file.status = 'error'
  //     }
  //   })
  // }
  //#endregion
</script>

<style lang="scss" scoped>
  .wrap {
    &-table {
      margin-top: 16px;
    }
  }
</style>
